package com.fmatos.amazingwallpapers.imagemanagement;

import java.io.InputStream;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.fmatos.amazingwallpapers.image.database.ImagesDataSource;
import com.fmatos.amazingwallpapers.image.database.dto.ImageRow;
import com.fmatos.amazingwallpapers.image.network.CloudHelper;
import com.fmatos.amazingwallpapers.image.network.dto.RemoteAlbumDeprecated;
import com.fmatos.amazingwallpapers.image.network.dto.RemotePhoto;

/**
 * Downloads and caches images
 * @author fdematos
 *
 */

@Deprecated
public class BitmapsDownloadManager {
	
	private static final String TAG = BitmapsDownloadManager.class.getSimpleName();
	private CloudHelper cloudHelper;
	
	
	public BitmapsDownloadManager() {
		cloudHelper = new CloudHelper();
	}
	/**
	 * Gets urls from server and downloads all images that aren't currently cached.
	 * Assumes this is not running on main thread
	 * @param datasource
	 * @param context 
	 * @return amount of new photos found
	 */
    @Deprecated
	public int downloadAllImagesFromAlbum(ImagesDataSource datasource, Context context) {
        Log.i(TAG,"Deprecated method to download album info");
        Toast.makeText(context,"Deprecated method to download album info",Toast.LENGTH_LONG).show();
        return 0;
   	}



    /**
	 * Download a single image that doesnt have a file
	 * @param datasource
	 * @param context
	 * @param maxImagesToDownload 
	 * @return
	 */
//	public int downloadImagesWithoutFile(ImagesDataSource datasource, Context context, int maxImagesToDownload) {
//		
////		String albumName = "sampleAlbum";
//				
//		int newPhotoCount = 0;
//        int failedDownloads = 0;
//		List<ImageRow> allImages = datasource.getAllImages();
//		
//		for (ImageRow image: allImages ) {
//			if ( downloadImageIfNeeded(image, image.getAlbum(), datasource, context) ) {
//				newPhotoCount++;
//			} else {
//                failedDownloads++;
//            }
//			
//			if ( newPhotoCount > maxImagesToDownload ) {
//				break;
//			}
//		}
//		
//		int remaining = allImages.size() - datasource.getImagesWithFiles().size();
//		Log.i(TAG,"Total photos downloaded = " + newPhotoCount + ", failed =" + failedDownloads);
//		Toast.makeText(context, "Download " + newPhotoCount + "/" + remaining + " images", Toast.LENGTH_SHORT).show();
//		
//		return newPhotoCount;
//	}


	/**
	 * 
	 * @param remoteAlbum
	 * @param dataSource
	 * @param context
	 * @return amount of new photos found (maybe not downloaded yet)
	 */
	private int storeAlbumInfo(RemoteAlbumDeprecated remoteAlbum, ImagesDataSource dataSource, Context context) {

		int newPhotoCount = 0;
		if ( remoteAlbum == null || remoteAlbum.getPhotos() == null) {
			return 0;
		}
		
		//Collections.reverse(remoteAlbum.getPhotos()); // so that newest images will appear at the end, and make a continous stream of images
		
		for (RemotePhoto image: remoteAlbum.getPhotos() ) {
			if ( insertImageOnDb(remoteAlbum.getName(),image,dataSource) ) {
				newPhotoCount++;
			}
				
		}
		Log.i(TAG,"Finished downloading album");
		// TODO optionally this could send broadcasts to interested parties (particularly, BitmapsRegrieverManager may be interested in it)
		
		return newPhotoCount;
	}
	
	/**
	 * Makes sure image is available on both disk and database.2 
	 * 
	 * When this method returns you're sure that this image is available locally
	 * 
	 * Must  ideal case:
	 * <li> check if url is available in database, and
	 * <li> check if database contains filename for this url
	 * <li> If necessary it proceeds to download image and update filename in DB 
	 * @param image
	 * @param dataSource
	 * @param albumName 
	 * @return true if URL wasn't known before
	 */
	private boolean insertImageOnDb(String albumName,RemotePhoto image,
			ImagesDataSource dataSource) {

		String safeUrl = image.getUrl();
		
		if ( safeUrl.contains(" ")) {
			safeUrl = image.getUrl().split(" ")[0]; // JPL is breaking this!
		}
 
		ImageRow row = dataSource.getImageFromUrl(safeUrl);
		
		boolean isNewUrl = false;
		
		if ( row == null ) {
			Log.i(TAG,"Insert new URL NOT" + safeUrl);
//			row = dataSource.createImageRow(safeUrl, image.getCaption(), albumName, image.getDescription());
			isNewUrl  = true;

		}
		
		return isNewUrl;
	}
	
	// TODO why do I need albumName???
//	public boolean downloadImageIfNeeded(ImageRow row, String albumName,
//				ImagesDataSource dataSource, Context context) {
//		
//		if ( ! dataSource.isOpen() ) {
//			return false;
//		}
//
//		
//		FileManager filemanager = new FileManager(context);
//		boolean isNewFile = false;
//
//		
//		if ( row.getFile() != null ) {
//			if ( ! filemanager.isFileExist(row.getFile()) ) {
//				row.setFile(null);
//				dataSource.updateFilename(row);
//			}
//		}
//		
//		if ( row.getFile() == null ) {
////			Log.i(TAG,"Downloading image and adding to database");
//			InputStream istream = cloudHelper.downloadImage(row.getUrl());
//			
//			if ( istream != null && dataSource.isOpen() ) {
//				String path = filemanager.writeFileToRandomPath(istream, row.getAlbum()); 
//				row.setFile(path);
//
//				dataSource.updateFilename(row);
//				isNewFile = true;
//				Log.i(TAG,"Downloaded new URL " + row.getCaption());
//
//			}
//		}
//		
//		
//		
//		return isNewFile;
//	}

}
